package com.efrei.schoolmanager.printing;

import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.OrientationRequested;

import com.sun.pdfview.PDFFile;

/**
 * Conversion d'un PDF en format imprimable
 */
public class PrintPdf {

	private PrinterJob pjob = null;

	public static void printPdf(String file) throws IOException,
			PrinterException {

		// Create a PDFFile from a File reference
		FileInputStream fis = new FileInputStream(file);
		PrintPdf printPDFFile = new PrintPdf(fis, "Test Print PDF");
		printPDFFile.print();
	}

	/**
	 * Construire le print job à partir de l'input stream
	 * 
	 * @param inputStream
	 * @param jobName
	 * @throws IOException
	 * @throws PrinterException
	 */
	public PrintPdf(InputStream inputStream, String jobName)
			throws IOException, PrinterException {
		byte[] pdfContent = new byte[inputStream.available()];
		inputStream.read(pdfContent, 0, inputStream.available());
		initialize(pdfContent, jobName);
	}

	/**
	 * Construire le print job à partir d'un tableau de byte
	 * 
	 * @param content
	 * @param jobName
	 * @throws IOException
	 * @throws PrinterException
	 */
	public PrintPdf(byte[] content, String jobName) throws IOException,
			PrinterException {
		initialize(content, jobName);
	}

	/**
	 * Initialiser le print job
	 * 
	 * @param pdfContent
	 * @param jobName
	 * @throws IOException
	 * @throws PrinterException
	 */
	private void initialize(byte[] pdfContent, String jobName)
			throws IOException, PrinterException {
		ByteBuffer bb = ByteBuffer.wrap(pdfContent);
		// Creer PDF Print Page
		PDFFile pdfFile = new PDFFile(bb);
		PDFPrintPage pages = new PDFPrintPage(pdfFile);

		// Creer Print Job
		pjob = PrinterJob.getPrinterJob();
		PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
		pjob.setJobName(jobName);
		Book book = new Book();
		book.append(pages, pf, pdfFile.getNumPages());
		pjob.setPageable(book);

		// Enlever les marges
		Paper paper = new Paper();
		paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
		pf.setPaper(paper);
	}

	public void print() throws PrinterException {
		HashPrintRequestAttributeSet printRequestSet = new HashPrintRequestAttributeSet();
		printRequestSet.add(OrientationRequested.LANDSCAPE);
		// Envoyer le print job au printer par défaut
		if (pjob.printDialog(printRequestSet)) {
			try {
				pjob.print();
			} catch (PrinterException ex) {
				ex.printStackTrace();
			}
		}
	}
}
